package com.jianbing.http;

import com.jianbing.util.StringUtils;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


/**
 * Created by Han, Tixiang on 2016/8/25 0025.
 */
public class HttpClient {
    private static Charset UTF_8 = Charset.forName("UTF-8");
    private static int defaultTimeout = 60000;
    private static Log log = LogFactory.getLog(HttpClient.class);

    public static String doGet(String url) throws Exception {
        return doGet(url, defaultTimeout, null, -1);
    }

    public static String doGet(String url, String proxyIp, int proxyPort) throws Exception {
        return doGet(url, defaultTimeout, proxyIp, proxyPort);
    }

    public static String doGet(String url, String proxyIp, int proxyPort, String proxyAccout, String proxyPass) throws Exception {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(defaultTimeout);
        client.getParams().setAuthenticationPreemptive(true);
        AuthScope authScope = new AuthScope(proxyIp, proxyPort);
        client.getState().setProxyCredentials(authScope, new UsernamePasswordCredentials(proxyAccout, proxyPass));
        if (proxyIp != null && proxyPort > 0) {
            client.getHostConfiguration().setProxy(proxyIp, proxyPort);
        }

        HttpMethod method = new GetMethod(url);
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception("notify failure");
            }

            // Read the response body.
            InputStream responseBody = method.getResponseBodyAsStream();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            StringBuffer buffer = new StringBuffer();
            byte[] bytes = new byte[1024];
            while (responseBody.read(bytes) != -1) {
                buffer.append(new String(bytes, UTF_8));
            }
            return buffer.toString();

        } catch (Exception e) {
          /*  if (!StringUtils.isEmpty(proxyIp) && proxyPort > 0) {
                log.error(proxyIp + ":" + proxyPort + " not avaliable");
            }
            log.error(e.toString(),e);*/
            throw e;
        } finally {
            method.releaseConnection();
        }
    }

    public static String doGet(String url, int timeout, String proxyIp, int proxyPort) throws Exception {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

        if (proxyIp != null && proxyPort > 0) {
            client.getHostConfiguration().setProxy(proxyIp, proxyPort);
        }

        HttpMethod method = new GetMethod(url);
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception("notify failure");
            }

            // Read the response body.
            InputStream responseBody = method.getResponseBodyAsStream();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            StringBuffer buffer = new StringBuffer();
            byte[] bytes = new byte[1024];
            while (responseBody.read(bytes) != -1) {
                buffer.append(new String(bytes, UTF_8));
            }
            return buffer.toString();

        } catch (Exception e) {
            if (!StringUtils.isEmpty(proxyIp) && proxyPort > 0) {
                log.error(proxyIp + ":" + proxyPort + " not avaliable");
            }
            log.error(e.toString(),e);
            throw e;
        } finally {
            method.releaseConnection();
        }
    }

    public static String doPost3(String url, Map params, byte[] inputStream) throws Exception {

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpPost postMethod = new HttpPost(url);
      /* File  file = new File("c:\\" + File.separator + System.currentTimeMillis() + ".jpg");
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(inputStream);*/
        FilePart cbFile = new FilePart("upload", new File("c:\\2.png"));
        Part[] parts = {cbFile};


        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "--------------------HV2ymHFg03ehbqgZCaKO6jyH", Charset.defaultCharset());

        multipartEntity.addPart("upload", new FileBody(new File("c:\\2.png")));

        multipartEntity.addPart("upload", new InputStreamBody(new ByteArrayInputStream(inputStream), ""));

        HttpPost request = new HttpPost("http://localhost:8080/sdkServlet");
        request.setEntity(multipartEntity);
        if (params != null && params.size() > 0) {
            Set set = params.entrySet();
            Iterator it = set.iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                if (entry.getValue() instanceof String) {
                    String val = (String) entry.getValue();
                    multipartEntity.addPart(key, new StringBody(val));
                }

            }

        }

        postMethod.setEntity(multipartEntity);
        try {
            // Execute the method.
            HttpResponse statusCode = httpClient.execute(postMethod);
            InputStream is = statusCode.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            System.out.println("发送消息收到的返回：" + buffer.toString());
           /* if (statusCode != HttpStatus.SC_OK) {
                throw new Exception("notify failure");
            }

            // Read the response body.
            InputStream responseBody = postMethod.getResponseBodyAsStream();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            StringBuffer buffer = new StringBuffer();
            byte[] bytes = new byte[1024];
            while (responseBody.read(bytes) != -1) {
                buffer.append(new String(bytes, UTF_8));
            }

            return buffer.toString();*/
            return "";
        } catch (Exception e) {
            log.error(e.toString(),e);
            throw e;
        } finally {
            postMethod.releaseConnection();
        }
    }

    public static String doPost(String url, Map params) throws Exception {
        log.info(url);
        log.info(params);
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(defaultTimeout);
        client.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        PostMethod method = new PostMethod(url);
        method.addRequestHeader("Content-Type", "text/html;charset=UTF-8");
        if (params != null && params.size() > 0) {
            Set set = params.entrySet();
            Iterator it = set.iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                if (entry.getValue() instanceof String) {
                    String val = (String) entry.getValue();
                    method.addParameter(key, val);
                }
            }
        }

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception("notify failure");
            }

            // Read the response body.
            InputStream responseBody = method.getResponseBodyAsStream();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            StringBuffer buffer = new StringBuffer();
            byte[] bytes = new byte[1024];
            while (responseBody.read(bytes) != -1) {
                buffer.append(new String(bytes, UTF_8));
            }
            log.info(buffer.toString());
            return buffer.toString();
        } catch (Exception e) {
            log.error("notify111111",e);
            throw e;
        } finally {
            method.releaseConnection();
        }
    }

    public static void doPost(String url, String json) throws Exception {

        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(defaultTimeout);
        PostMethod method = new PostMethod(url);
        method.setRequestEntity(new StringRequestEntity(json, "text/plain", "UTF-8"));
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception("notify failure");
            }

            // Read the response body.
            InputStream responseBody = method.getResponseBodyAsStream();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            StringBuffer buffer = new StringBuffer();
            byte[] bytes = new byte[1024];
            while (responseBody.read(bytes) != -1) {
                buffer.append(new String(bytes, UTF_8));
            }
            log.info(buffer.toString());

        } catch (Exception e) {
            log.error(e.toString(),e);
            throw e;
        } finally {
            method.releaseConnection();
        }
    }


    public static void main(String[] args) throws Exception {

        String url = "http://localhost:4821/api/gjjdata";
        Map map = new HashMap();
        map.put("cityId", "2");

        String s = HttpAsynClient.doGet(url);
        System.out.println(s);
        //doGet("http://www.baidu.com/", "112.175.67.185", 8888);


    }
}
